package cn.edu.zsc.study.common.util;

import cn.edu.zsc.study.entity.Dept;
import cn.edu.zsc.study.exception.NotExistException;

import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

/**
 * @author Yao
 */
public class DeptTreeUtil {

    public static Dept initTree(HashSet<Dept> list){
        Dept rootDept = list.stream()
                .filter(dept -> dept.getPid() == null)
                .findFirst()
                .orElseThrow(NotExistException::new);
        rootDept.children = DeptTreeUtil.getTree(list, rootDept.id);
        return rootDept;
    }

    public static HashSet<Dept> getTree(HashSet<Dept> list, long parentId){
        //获取所有子节点
        HashSet<Dept> childTreeList = getChildTree(list, parentId);
        for (Dept dept:childTreeList) {
            dept.setChildren(getTree(list, dept.id));
        }
        return childTreeList;
    }

    public static HashSet<Dept> getChildTree(HashSet<Dept> list, long id){
        HashSet<Dept> childTree = new HashSet<>();
        for (Dept dept: list) {
            if(dept.getPid() != null && dept.getPid() == id){
                childTree.add(dept);
            }
        }
        return childTree;
    }

    /**
     * 从部门树中获取子树
     * @param list
     * @return
     */
    public static Dept getChildNode(Set<Dept> list, long id) {
        Stack<Dept> deptStack = new Stack<>();
        deptStack.addAll(list);
        while (!deptStack.isEmpty()) {
            Dept child = deptStack.pop();
            if (child.getId() == id) {
                return child;
            } else if (child.children != null && !child.children.isEmpty()) {
                deptStack.addAll(child.children);
            }
        }
//        for (Dept child: list) {
//            if (child.id == id) {
//                return child;
//            } else if (child.children != null && !child.children.isEmpty()) {
//                return getChildNode(child.children, id);
//            }
//        }
        return null;
    }


    /**
     * 从部门获取本身及子部门的所有id
     * @param dept
     * @return
     */
    public static HashSet<Long> getDeptPath(Dept dept) {
        HashSet<Long> result = new HashSet<>();
        result.add(dept.getId());
        Stack<Dept> deptStack = new Stack<>();
        if (dept.children.size() > 0) {
            deptStack.addAll(dept.children);
            while (!deptStack.isEmpty()) {
                Dept child = deptStack.pop();
                result.add(child.getId());
                if (child.children.size() > 0) {
                    deptStack.addAll(child.children);
                }
            }
        }
        return result;
    }
}
